with Interfaces.C.Pointers;
with Interfaces.C.Strings;
with Ada.Unchecked_Conversion;

package body FT2.Types is

   package Byte_Pointers is new Interfaces.C.Pointers
     (Natural, FT_Byte, FT_Byte_Array, 0);

   package Short_Pointers is new Interfaces.C.Pointers
     (Natural, FT_Short, FT_Short_Array, 0);

   function To_chars_ptr is new Ada.Unchecked_Conversion
     (FT_String_Ptr, Interfaces.C.Strings.chars_ptr);

   ---------------------
   -- Check_And_Raise --
   ---------------------

   procedure Check_And_Raise (Error : FT_Error) is
   begin
      if Error /= 0 then
         raise FT_Exception with FT_Error'Image (Error);
      end if;
   end Check_And_Raise;

   ---------------
   -- Get_Error --
   ---------------

   function Get_Error
     (X : Ada.Exceptions.Exception_Occurrence)
      return FT_Error
   is
      use Ada.Exceptions;
   begin
      if Exception_Identity (X) = FT_Exception'Identity then
         begin
            return FT_Error'Value (Exception_Message (X));
         exception
            when others =>
               return 0;
         end;
      else
         return 0;
      end if;
   end Get_Error;

   --------------
   -- To_Array --
   --------------

   function To_Array
     (Ptr : FT_Bytes_Ptr;
      Length : FT_Int)
      return FT_Byte_Array
   is
   begin
      return Byte_Pointers.Value
        (Byte_Pointers.Pointer (Ptr), Interfaces.C.ptrdiff_t (Length));
   end To_Array;

   --------------
   -- To_Array --
   --------------

   function To_Array
     (Ptr : FT_Shorts_Ptr;
      Length : FT_Int)
      return FT_Short_Array
   is
   begin
      return Short_Pointers.Value
        (Short_Pointers.Pointer (Ptr), Interfaces.C.ptrdiff_t (Length));
   end To_Array;

   ---------------
   -- To_String --
   ---------------

   function To_String (Ptr : FT_String_Ptr) return String is
   begin
      return Interfaces.C.Strings.Value (To_chars_ptr (Ptr));
   end To_String;

end FT2.Types;
